package com.qf.mybatis01.servlet;

import com.qf.mybatis01.dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/reset")
public class ResetServlet extends HttpServlet {

    // 创建  SqlSessionFactoryBuilder 对象
    final SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

    // mybatis-config.xml  --->   inputStream
//        final InputStream inputStream = getClass().getResourceAsStream("/mybatis-config.xml");

    final InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

    // 创建 SqlSessionFactory
    SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);

    public ResetServlet() throws IOException {
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // Mybatis的 核心对象 是 SqlSession
        SqlSession sqlSession = sessionFactory.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        final Integer result = userDao.resetUsers();

        sqlSession.commit();

        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println("重置了"+result+"个同学");



    }
}
